<template>
  <div class="exam-management-page">
    <!-- 培训班基本信息 -->
    <div class="class-info">
      <span class="info-item">培训班编号：{{ trainingClassCode || "123456" }}</span>
      <span class="info-item">培训班名称：{{ className || "XXX" }}</span>
    </div>

    <!-- 搜索区域 -->
    <el-form
      v-if="showSearch"
      :inline="true"
      :model="searchForm"
      class="search-form"
      label-width="60px"
    >
      <el-form-item label="姓名">
        <el-input v-model="searchForm.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="证件编号" label-width="120">
        <el-input v-model="searchForm.idCard" placeholder="请输入证件编号" />
      </el-form-item>
      <el-form-item label="是否通过" label-width="120">
        <el-select v-model="searchForm.isPass" placeholder="选择是否通过" style="width:100px">
          <el-option label="全部" value="" />
          <el-option label="通过" value="0" />
          <el-option label="未通过" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="考试状态" label-width="120">
        <el-select v-model="searchForm.examStatus" placeholder="选择考试状态" style="width:100px">
          <el-option label="全部" value="" />
          <el-option label="已考试" value="0" />
          <el-option label="未考试" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮栏 -->
    <div class="operation-buttons">
      <el-button type="primary" plain>导出</el-button>
      <el-button type="primary" plain @click="openSpecialExam">特设考试</el-button>
      <el-button type="primary" plain @click="openPersonalExam" :disabled="!selection || selection.length !== 1">学员个人考试</el-button>
      <el-button type="primary" plain @click="examSchedule">考试安排</el-button>
      <el-button type="primary" plain @click="openRemarkDialog" :disabled="!selection || selection.length === 0">学员备注</el-button>
      <el-button type="primary" plain @click="openNoticeDialog" :disabled="!selection || selection.length === 0">学员通知</el-button>
      <el-button type="primary" plain @click="handleMakeupExam" :disabled="!selection || selection.length !== 1">多次补考</el-button>
      <el-button type="primary" plain @click="handleQrCode" >考试二维码</el-button>
      <el-button type="primary" plain @click="handleExamDetail(selection.length > 0 ? selection[0] : null)" :disabled="!selection || selection.length === 0">考试详情</el-button>
      <el-button type="primary" plain @click="toggleSearch">
        {{ showSearch ? "隐藏搜索" : "显示搜索" }}
      </el-button>
      <el-button type="primary" plain @click="handleRefresh">刷新</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      stripe
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="姓名" width="80" />
      <el-table-column prop="idCard" label="证件编号" width="180" />
      <el-table-column prop="projectName" label="项目" width="180" />
      <el-table-column prop="gender" label="性别" width="60" />
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column prop="examStatus" label="考试状态" width="100" />
      <el-table-column prop="examTimes" label="考试次数" width="100" />
      <el-table-column prop="examScore" label="考试成绩" width="100" />
      <el-table-column prop="isPass" label="是否通过" width="100">
        <template #default="scope">
          <span :style="{ color: scope.row.isPass === '通过' ? 'green' : 'red' }">
            {{ scope.row.isPass }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="makeupExam" label="补考情况" width="100" />
      <el-table-column prop="makeupMark" label="补考标记" width="100" />
      <el-table-column prop="remark" label="备注" width="120" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button type="text" @click="handleExamDetail(scope.row)">考试详情</el-button>
          <el-button type="text" @click="openRemarkDialog(scope.row)">备注</el-button>
          <el-button type="text" @click="openNoticeDialog(scope.row)">学员通知</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      />
    </div>

    <!-- 考试安排弹窗 -->
    <el-dialog
      title="考试安排"
      :visible.sync="dialogVisibleExamArrangement"
      width="900px"
      @close="handleCancelExamArrangement"
    >
    <div class="form-group">
          <h4 class="group-title">培训考试</h4>
          <div class="table-wrapper">
            <el-table :data="exams" border style="width: 90%;" class="custom-table">
              <el-table-column label="考试题组" width="250px">
                <template #default="scope">
                  <el-select
                    v-model="scope.row.group"
                    placeholder="请选择考试"
                    class="custom-input"
                    @change="handlePaperConfigChange(scope.row, scope.row.group)"
                    disabled
                  >
                    <el-option
                      v-for="item in paperConfigOptions"
                      :key="item.paperConfigId"
                      :label="item.paperConfigName"
                      :value="item.paperConfigId"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="单选题题量" prop="singleChoiceCount">
                <template #default="scope">
                  <el-input v-model.number="scope.row.singleChoiceCount" placeholder="单选题题量" class="custom-input" disabled></el-input>
                </template>
              </el-table-column>
              <el-table-column label="多选题题量" prop="multipleChoiceCount">
                <template #default="scope">
                  <el-input v-model.number="scope.row.multipleChoiceCount" placeholder="多选题题量" class="custom-input" disabled></el-input>
                </template>
              </el-table-column>
              <el-table-column label="判断题题量" prop="judgmentCount">
                <template #default="scope">
                  <el-input v-model.number="scope.row.judgmentCount" placeholder="判断题题量" class="custom-input" disabled></el-input>
                </template>
              </el-table-column>
              <el-table-column label="合计题量" prop="totalCount">
                <template #default="scope">
                  <el-input v-model.number="scope.row.totalCount" placeholder="合计题量" class="custom-input" disabled></el-input>
                </template>
              </el-table-column>
              <el-table-column label="分数合计" prop="totalScore"></el-table-column>
            </el-table>
          </div>
        </div>

      <el-form
        :model="formExamArrangement"
        :rules="rulesExamArrangement"
        ref="formRef"
        label-width="140px"
        class="exam-form"
      >
        <!-- 第一行：考试时间相关 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="考试开始时间" prop="examStartTime">
              <el-date-picker
                v-model="formExamArrangement.examStartTime"
                type="datetime"
                placeholder="请选择考试开始时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试结束时间" prop="examEndTime">
              <el-date-picker
                v-model="formExamArrangement.examEndTime"
                type="datetime"
                placeholder="请选择考试结束时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：时长和地址 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="考试时长（分钟）" prop="examDuration">
              <el-input
                v-model.number="formExamArrangement.examDuration"
                placeholder="请输入考试时长"
                type="number"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试地址" prop="examAddress">
              <el-input
                v-model="formExamArrangement.examAddress"
                placeholder="请输入考试地址[地址定位]"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：考试途径和通过分数 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="考试途径" prop="examWays">
              <el-checkbox-group v-model="formExamArrangement.examWays">
                <el-checkbox label="手机" style="margin-right: 20px">手机</el-checkbox>
                <el-checkbox label="电脑">电脑</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试通过分数" prop="passScore">
              <el-input
                v-model.number="formExamArrangement.passScore"
                placeholder="请输入考试通过分数"
                type="number"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行：成绩发布设置 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否提交后立刻发布成绩" prop="publishImmediately" label-width="250px">
              <el-radio-group v-model="formExamArrangement.publishImmediately" @change="handlePublishChange">
                <el-radio label="是" style="margin-right: 20px">是</el-radio>
                <el-radio label="否">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成绩发布时间" prop="publishTime">
              <el-date-picker
                v-model="formExamArrangement.publishTime"
                type="datetime"
                placeholder="请选择成绩发布时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                :disabled="formExamArrangement.publishImmediately === '是'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行：补考设置 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否同意自动补考" prop="autoMakeup" label-width="250px">
              <el-radio-group v-model="formExamArrangement.autoMakeup">
                <el-radio label="是" style="margin-right: 20px">是</el-radio>
                <el-radio label="否">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="补考次数" prop="makeupTimes">
              <el-input
                v-model.number="formExamArrangement.makeupTimes"
                placeholder="请输入可补考次数"
                type="number"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第六行：监考人员 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="监考人员" prop="invigilator">
              <el-select v-model="formExamArrangement.invigilator" placeholder="请选择监考人员" style="width: 100%">
                <el-option
                  v-for="item in invigilatorOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第七行：备注 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="formExamArrangement.remark"
                type="textarea"
                :rows="4"
                placeholder="请输入备注"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 底部按钮 -->
        <el-row>
          <el-col :span="24" class="form-footer">
            <el-button @click="handleCancelExamArrangement">取消</el-button>
            <!-- 上一个按钮 -->
            <el-button
              type="primary"
              plain
              @click="handlePrevSchedule"
              v-if="examScheduleList.length > 1"
              :disabled="currentScheduleIndex === 0"
              style="margin-left: 10px;"
            >
              上一个
            </el-button>
            <el-button
              type="primary"
              plain
              @click="handleNextSchedule"
              v-if="examScheduleList.length > 1"
              :disabled="currentScheduleIndex === examScheduleList.length-1"
              style="margin-left: 10px;"
            >
              下一页
            </el-button>
            <el-button type="primary" @click="handleSubmitExamArrangement" style="margin-left: 10px;">提交</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- 学员通知弹窗（移植自培训班页面，适配考试场景） -->
    <el-dialog
      title="发送学员通知"
      :visible.sync="noticeDialogVisible"
      width="50%"
      :before-close="handleNoticeDialogClose"
    >
      <el-form :model="noticeForm" ref="noticeForm" :rules="noticeRules">
        <!-- 通知类型（短信/门户）- 移植核心功能 -->
        <el-form-item label="通知类型" prop="sendTypes">
          <el-checkbox-group v-model="noticeForm.sendTypes">
            <el-checkbox label="0">短信</el-checkbox>
            <el-checkbox label="1">门户</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 通知标题 -->
        <!-- <el-form-item label="通知标题" prop="title">
          <el-input v-model="noticeForm.title" placeholder="请输入通知标题"></el-input>
        </el-form-item> -->

        <!-- 通知内容 -->
        <el-form-item label="通知内容" prop="content">
          <el-input
            type="textarea"
            v-model="noticeForm.content"
            placeholder="请输入通知内容"
            rows="6"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>

        <!-- 发送范围 -->
        <el-form-item label="发送范围">
          <el-radio-group v-model="noticeForm.range" @change="handleRangeChange">
            <el-radio label="all">所有学员</el-radio>
            <el-radio label="selected">指定学员</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 指定学员选择（远程搜索+选中计数）- 移植核心功能 -->
        <el-form-item
          v-if="noticeForm.range === 'selected'"
          class="selected-users-form-item"
          prop="selectedUsers"
          :rules="[{ required: true, message: '请至少选择一个学员', trigger: 'change' }]"
        >
          <el-select
            v-model="noticeForm.selectedUsers"
            multiple
            placeholder="请输入学员姓名搜索并选择"
            filterable
            remote
            :remote-method="queryUsers"
            :loading="userLoading"
            style="width: 100%;"
            clearable
            @clear="handleSelectClear"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            >
              <span style="float: left">{{ user.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                身份证号：{{ user.idCard || '无证件号' }}
              </span>
            </el-option>
            <template #empty>
              <div style="text-align: center; color: #909399;">
                {{ userLoading ? '搜索中...' : '无匹配学员，请更换关键词' }}
              </div>
            </template>
          </el-select>
          <div class="selected-count" v-if="noticeForm.range === 'selected'">
            已选择 {{ noticeForm.selectedUsers.length }} 名学员
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="noticeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitNotice" :loading="noticeLoading">发送</el-button>
      </div>
    </el-dialog>

    <!-- 学员备注弹窗（移植自培训班页面，适配考试场景） -->
    <el-dialog
      :title="remarkDialogTitle"
      :visible.sync="remarkDialogVisible"
      width="60%"
      size="mini"
      @close="resetRemarkForm"
    >
      <el-form ref="remarkForm" :model="remarkForm" label-width="80px" :rules="remarkRules" class="remark-form">
        <!-- 备注输入框（带字数限制）- 移植核心功能 -->
        <el-form-item label="备注内容" prop="remarks">
          <el-input
            v-model="remarkForm.remarks"
            type="textarea"
            :rows="4"
            placeholder="请输入备注内容"
            style="width: 100%"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>

        <!-- 备注历史记录（表格展示）- 移植核心功能 -->
        <el-form-item label="备注历史" label-width="80px">
          <el-table
            :data="remarkHistory"
            border
            stripe
            size="mini"
            :cell-style="{ 'vertical-align': 'middle' }"
            style="width: 100%;"
            :loading="remarkLoading"
            empty-text="暂无备注记录"
          >
            <el-table-column prop="time" label="时间" align="center" width="180" />
            <el-table-column prop="operator" label="备注人" align="center" width="120" />
            <el-table-column prop="content" label="备注" align="left" />
          </el-table>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="mini" @click="remarkDialogVisible = false">取消</el-button>
          <el-button size="mini" type="primary" @click="submitRemark" :loading="remarkSubmitting">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 考试二维码弹窗（移植班级二维码功能，适配考试场景） -->
    <el-dialog
      title="考试二维码"
      :visible.sync="qrCodeDialogVisible"
      width="300px"
      @close="resetCode"
      center
    >
      <div class="qr-code-container">
        <!-- 二维码图片+错误处理 - 移植核心功能 -->
        <img
          v-if="!qrcodeError"
          :src="qrCodeUrl"
          alt="考试二维码"
          class="qr-code-image"
          @error="handleQrcodeError"
        >
        <div v-if="qrcodeError" class="qrcode-error">
          二维码图片加载失败，请稍后重试
        </div>
        <p class="qr-code-desc">请让学员扫描此二维码参加考试</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="qrCodeDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 考试详情弹窗 -->
    <el-dialog
      :title="`${currentStudent.name || ''}的考试详情`"
      :visible.sync="examDetailDialogVisible"
      width="800px"
      @close="handleCloseExamDetail"
    >
      <div class="exam-detail-container">
        <!-- 基本信息区域 -->
        <div class="detail-section">
          <h3 class="section-title">基本信息</h3>
          <el-row :gutter="20">
            <!-- <el-col :span="8">
              <div class="detail-item">
                <span class="item-label">编号：</span>
                <span class="item-value">{{ currentStudent.id || '-' }}</span>
              </div>
            </el-col> -->
            <el-col :span="8">
              <div class="detail-item">
                <span class="item-label">姓名：</span>
                <span class="item-value">{{ currentStudent.name || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <span class="item-label">性别：</span>
                <span class="item-value">{{ currentStudent.gender || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="item-label">证件编号：</span>
                <span class="item-value">{{ currentStudent.idCard || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="item-label">联系电话：</span>
                <span class="item-value">{{ currentStudent.phone || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="detail-item">
                <span class="item-label">单位名称：</span>
                <span class="item-value">{{ currentStudent.company || '-' }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 考试状态信息 -->
        <div class="detail-section">
          <h3 class="section-title">考试状态</h3>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="detail-item">
                <span class="item-label">考试状态：</span>
                <span class="item-value">{{ currentStudent.examStatus || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-item">
                <span class="item-label">考试次数：</span>
                <span class="item-value">{{ currentStudent.examTimes || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-item">
                <span class="item-label">考试成绩：</span>
                <span class="item-value">{{ currentStudent.examScore || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="detail-item">
                <span class="item-label">是否通过：</span>
                <span class="item-value" :style="{ color: currentStudent.isPass === '通过' ? 'green' : 'red' }">
                  {{ currentStudent.isPass || '-' }}
                </span>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 补考信息 -->
        <div class="detail-section">
          <h3 class="section-title">补考信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="item-label">补考情况：</span>
                <span class="item-value">{{ currentStudent.makeupExam || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="item-label">补考标记：</span>
                <span class="item-value">{{ currentStudent.makeupMark || '-' }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 考试记录 -->
        <div class="detail-section">
        <h3 class="section-title">考试记录</h3>
        <el-table
          :data="examRecords"
          border
          size="small"
          style="width: 100%;"
        >
          <!-- <el-table-column prop="examNo" label="考试编号" width="150" /> -->
          <el-table-column prop="examDate" label="考试日期" />
          <!-- <el-table-column prop="examType" label="考试类型" width="120" /> -->
          <el-table-column prop="score" label="成绩" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <span :style="{ color: scope.row.status === '通过' ? 'green' : 'red' }">
                {{ scope.row.status }}
              </span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="invigilator" label="监考人员" /> -->
          <!-- 新增操作列 -->
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                type="text"
                @click="openExamPaperDialog(scope.row)"
                size="small"
              >
                查看考卷
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

        <!-- 备注信息 -->
        <div class="detail-section">
          <h3 class="section-title">备注信息</h3>
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="detail-item">
                <span class="item-label">备注内容：</span>
                <span class="item-value">{{ currentStudent.remark || '无' }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <div style="margin-top: 20px; text-align: center;">
        <el-button @click="examDetailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 多次补考设置弹窗 -->
    <el-dialog
      title="多次补考设置"
      :visible.sync="makeupExamDialogVisible"
      width="600px"
      @close="handleCloseMakeupExam"
    >
      <div class="selected-students">
        <h4>已选择学员（{{ selectedStudents.length }}人）</h4>
        <el-tag
          v-for="student in selectedStudents"
          :key="student.id"
          closable
          @close="removeStudent(student.id)"
          style="margin-right: 5px; margin-bottom: 5px;"
        >
          {{ student.name }}（{{ student.id }}）
        </el-tag>
      </div>

      <el-form :model="makeupExamForm" :rules="makeupExamRules" ref="makeupExamFormRef" label-width="120px">
        <el-form-item label="允许补考次数" prop="makeupTimes">
          <el-input v-model.number="makeupExamForm.makeupTimes" type="number" placeholder="请输入允许的补考次数" />
        </el-form-item>
        <el-form-item label="补考时间范围" prop="makeupTimeRange">
          <el-date-picker
            v-model="makeupExamForm.makeupTimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="是否自动安排补考" prop="autoMakeup" label-width="150px">
          <el-radio-group v-model="makeupExamForm.autoMakeup">
            <el-radio label="是" />
            <el-radio label="否" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="补考备注" label-width="150px">
          <el-input v-model="makeupExamForm.remark" type="textarea" rows="3" placeholder="请输入补考相关备注" />
        </el-form-item>

        <div style="text-align: center; margin-top: 20px;">
          <el-button @click="makeupExamDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitMakeupExam">确定</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 考卷详情弹窗 -->
  <el-dialog
    title="考卷详情"
    :visible.sync="examPaperDialogVisible"
    width="90%"
    max-height="80vh"
    :close-on-click-modal="false"
  >
    <div class="exam-paper-container">
      <!-- <div class="paper-header">
        <div class="paper-info">
          <p>考试编号: {{ currentExamPaper.examNo }}</p>
          <p>考试日期: {{ currentExamPaper.examDate }}</p>
          <p>总分: {{ currentExamPaper.score }}</p>
        </div>
      </div> -->

      <div class="questions-container">
        <div
          class="question-item"
          v-for="(question, index) in currentExamPaper.questions"
          :key="question.questionId"
        >
          <div class="question-header">
            <span class="question-index">{{ index + 1 }}.</span>
            <span class="question-type">
              {{ getQuestionType(question.questionType) }}
            </span>
          </div>
          <div class="question-content">
            {{ question.questionName }}
          </div>

          <!-- 选项展示 -->
          <div v-if="question.questionOptionList && question.questionOptionList.length > 0" class="question-options">
            <div
              class="option-item"
              v-for="option in question.questionOptionList"
              :key="option.optionId"
              :class="{
                'correct-option': option.optionName === question.answer,
                'student-option': option.optionName === question.studentAnswer
              }"
            >
              <span class="option-label">{{ option.optionName }}.</span>
              <span class="option-content">{{ option.optionContent }}</span>
            </div>
          </div>

          <!-- 答案和解析 -->
          <div class="question-answer">
            <div class="answer-label">参考答案: {{ question.answer || '无' }}</div>
            <div v-if="question.studentAnswer" class="student-answer">
              你的答案: {{ question.studentAnswer }}
            </div>
            <div v-if="question.analysisContent" class="answer-analysis">
              解析: {{ question.analysisContent }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <el-button @click="examPaperDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
  </div>
</template>

<script>
// 引入原有考试相关API
import {
  getExamListByClassId,getExamRecordInfo
} from "@/api/examination/examRecord";
import {
  getExamSchedule, addExamSchedule, updateExamSchedule, listExamSchedule
} from "@/api/training/examSchedule";
import {
  getTrainingClass,queryExams,getExamInfoById
} from "@/api/training/TrainingClass";
import {
  getPaperConfig,getPaperCofigList
} from "@/api/examination/paperConfig";
// 引入移植功能所需API（来自培训班页面）
import {
  listRemarksByParams,
  addRemarks
} from "@/api/training/remarks";
import {
  studentNoticeProcess
} from "@/api/training/studentNotice.js";

export default {
  name: "ExamManagement",
  data() {
    return {
      // 新增考卷弹窗相关数据
      examPaperDialogVisible: false,
      currentExamPaper: {
        examNo: '',
        examDate: '',
        score: '',
        questions: []
      },
      // 搜索与表格基础数据
      searchForm: { name: "", idCard: "", isPass: "", examStatus: "" },
      single: true,
      tableData: [],
      pagination: { currentPage: 1, pageSize: 10, total: 0 },
      showSearch: true,
      selection: null,
      selectedStudents: [],
      currentStudent: {}, // 当前查看详情的学员
      userFlagId: null, // 当前登录用户ID（用于备注/通知操作）

      // 考试安排弹窗数据
      dialogVisibleExamArrangement: false,
      formExamArrangement: {
        paperConfigId:"",
        examScheduleId: "",
        trainingClassId: "",
        examStartTime: "",
        examEndTime: "",
        examDuration: "",
        examAddress: "",
        examWays: ["手机", "电脑"],
        passScore: "",
        publishImmediately: "是",
        publishTime: "",
        autoMakeup: "是",
        makeupTimes: "",
        invigilator: "",
        remark: "",
      },
      // 考试相关数据
      paperConfigOptions: [], // 考试题组选项
      exams: [{
        group: '',
        singleChoiceCount: null,
        multipleChoiceCount: null,
        judgmentCount: null,
        totalCount: null,
        totalScore: null
      }],
      invigilatorOptions: [
        { value: '1', label: '张老师' },
        { value: '2', label: '李老师' },
        { value: '3', label: '王老师' }
      ],
      rulesExamArrangement: {
        examStartTime: [{ required: true, message: "请选择考试开始时间", trigger: "change" }],
        examEndTime: [{ required: true, message: "请选择考试结束时间", trigger: "change" }],
        examDuration: [{ required: true, message: "请输入考试时长", trigger: "blur" }],
        examAddress: [{ required: true, message: "请输入考试地址", trigger: "blur" }],
        examWays: [{ required: true, message: "请选择考试途径", trigger: "change" }],
        passScore: [{ required: true, message: "请输入考试通过分数", trigger: "blur" }],
        publishImmediately: [{ required: true, message: "请选择是否立即发布成绩", trigger: "change" }],
        makeupTimes: [{ required: true, message: "请输入补考次数", trigger: "blur" }],
        invigilator: [{ required: true, message: "请选择监考人员", trigger: "change" }]
      },
      examScheduleList: [], // 存储当前班级的所有考试安排
      currentScheduleIndex: 0, // 当前选中的考试安排索引

      // 学员通知弹窗数据（移植自培训班页面，补全字段）
      noticeDialogVisible: false,
      noticeLoading: false,
      noticeForm: {
        title: '',
        content: '',
        range: 'all',
        selectedUsers: [],
        sendTypes: [] // 0=短信，1=门户（移植核心字段）
      },
      noticeRules: {
        sendTypes: [{ required: true, message: '请选择通知类型', trigger: 'change' }], // 移植核心校验
        // title: [{ required: true, message: "请输入通知标题", trigger: "blur" }],
        content: [{ required: true, message: "请输入通知内容", trigger: "blur" }, { max: 500, message: '内容不能超过500个字符', trigger: 'blur' }],
        selectedUsers: [{ required: true, message: '请选择人员', trigger: 'change' }], // 移植核心校验
     },
      userLoading: false,
      userOptions: [],
      allUsers: [], // 存储所有学员数据（用于通知搜索）

      // 学员备注弹窗数据（移植自培训班页面，补全字段）
      remarkDialogVisible: false,
      remarkDialogTitle: "学员备注",
      remarkForm: { remarks: "", studentId: null }, // 新增studentId关联学员
      remarkHistory: [],
      remarkLoading: false, // 备注历史加载状态
      remarkSubmitting: false, // 备注提交状态
      remarkRules: {
        remarks: [{ required: true, message: "请输入备注内容", trigger: "blur" }] // 移植核心校验
      },

      // 考试二维码弹窗数据（移植班级二维码功能，补全字段）
      qrCodeDialogVisible: false,
      qrCodeUrl: 'http://127.0.0.1:9300/statics/2025/09/19/1_20250919113028A006.jpg', // 移植默认URL
      qrcodeError: false, // 二维码加载错误状态

      // 考试详情相关
      examDetailDialogVisible: false,
      examRecords: [],

      // 多次补考相关
      makeupExamDialogVisible: false,
      makeupExamForm: {
        makeupTimes: 1,
        makeupTimeRange: [],
        autoMakeup: "否",
        remark: ""
      },
      makeupExamRules: {
        makeupTimes: [{ required: true, message: "请输入允许的补考次数", trigger: "blur" }],
        makeupTimeRange: [{ required: true, message: "请选择补考时间范围", trigger: "change" }],
        autoMakeup: [{ required: true, message: "请选择是否自动安排补考", trigger: "change" }]
      },

      // 父组件参数
      classId: "",
      className: "",
      trainingClassCode: "",
      handoverStatus: "",
    };
  },
  watch: {
    '$route.query.classId': {
      immediate: true,
      handler(newId) {
        const params = this.$route.params;
        this.classId = params.classId;
        this.className = params.className;
        this.trainingClassCode = params.trainingClassCode;
        this.handoverStatus = params.handoverStatus;
        this.getList();
      }
    }
  },
  created() {
    // 获取当前登录用户ID（用于备注/通知操作）
    this.userFlagId = this.$store.state.user.id;
  },
  methods: {
    // 加载考试记录（修改为使用真实数据）
    async loadExamRecords(studentId) {
      try {
        const res = await getExamRecordInfo({
          studentId: this.currentStudent.id,
          trainingClassId: this.classId,
        });

        if (res.code === 200 && Array.isArray(res.rows) && res.rows.length > 0) {
          // 处理外层考试记录数据
          this.examRecords = res.rows.map(record => ({
            examNo: record.examNumber || `K${record.createTime.split(' ')[0].replace(/-/g, '')}${record.studentId.slice(-6)}`,
            examDate: record.createTime ? record.createTime.split(' ')[0] : '',
            examType: this.getExamType(record.examFrequency),
            score: record.totalScore || '0',
            status: this.getExamStatus(record.examResult, record.theoryResult),
            invigilator: record.invigilator || '未知',
            // 保存原始记录数据，用于查看考卷
            originalRecord: record
          }));
        } else {
          this.examRecords = [];
          this.$message.warning('未查询到考试记录');
        }
      } catch (error) {
        this.$message.error('加载考试记录失败');
        console.error('加载考试记录错误:', error);
        this.examRecords = [];
      }
    },

    // 打开考卷详情弹窗
    openExamPaperDialog(record) {
      this.currentExamPaper = {
        examNo: record.examNo,
        examDate: record.examDate,
        score: record.score,
        questions: record.originalRecord.examRecordInfoDtoList || []
      };
      this.examPaperDialogVisible = true;
    },

    // 辅助方法：获取考试类型文本
    getExamType(frequency) {
      if (!frequency || frequency === '1') return '正式考试';
      return `第${frequency}次补考`;
    },

    // 辅助方法：获取考试状态文本
    getExamStatus(examResult, theoryResult) {
      // 优先使用整体考试结果
      if (examResult === '通过' || examResult === '0') return '通过';
      if (examResult === '未通过' || examResult === '1') return '未通过';

      // 没有整体结果时使用理论考试结果
      if (theoryResult === '0') return '通过';
      if (theoryResult === '1') return '未通过';

      // 其他状态
      return '待评价';
    },

    // 辅助方法：获取题目类型文本
    getQuestionType(type) {
      const typeMap = {
        '1': '单选题',
        '2': '多选题',
        '3': '判断题'
      };
      return typeMap[type] || `题型${type}`;
    },
    // -------------- 原有考试管理核心方法 --------------
    async getList() {
      try {
        const res = await getExamListByClassId({
          trainingClassId: this.classId,
          studentName: this.searchForm.name,
          idNumber: this.searchForm.idCard,
          examStatus: this.searchForm.examStatus,
          examResult: this.searchForm.isPass,
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        });

        if (res.code !== 200 || !Array.isArray(res.rows)) {
          this.$message.error("数据加载失败，请重试");
          return;
        }
        this.tableData = res.rows.map(item => ({
          id: item.studentId || "-",
          name: item.studentName || "-",
          idCard: item.idNumber || "-",
          gender: item.sex==="M"?"男":"女" || "-",
          phone: item.phonenumber || "-",
          company: item.unitName || "-",
          examStatus: item.examStatus || "-",
          examTimes: item.examFrequency || "0",
          examScore: item.totalScore || "",
          isPass: item.examResult || "",
          makeupExam: item.makeUpStatus || "-",
          makeupMark: item.makeUpMark || "-",
          remark: item.examRecordRemark || "",
          projectName:item.projectName||""
        }));

        this.pagination.total = res.total || 0;

        // 初始化学员数据（用于通知弹窗搜索）
        this.allUsers = [...this.tableData];
        this.userOptions = this.tableData.map(u => ({
          id: u.id,
          name: u.name,
          idCard: u.idCard // 补全身份证号（用于通知弹窗显示）
        }));

      } catch (error) {
        this.$message.error("获取数据失败，请检查网络");
        console.error("接口请求错误:", error);
      }
    },

    async openPersonalExam() {
      const resClass= await getTrainingClass(this.classId);
      let projectId=resClass.data.trainingProject
      this.$router.push({
        name: '学员个人考试',
        params: {
          classId: this.classId ||"",
          className: this.className ||"",
          trainingClassCode: this.trainingClassCode ||"",
          name: this.selection[0].name ||"",
          idCard: this.selection[0].idCard ||"",
          studentId:this.selection[0].id ||"",
          projectId:projectId ||""
        }
      });
    },
    openSpecialExam() {
      this.$router.push({
        name: '特设考试',
        params: {
          classId: this.classId,
          className: this.className,
          classStatus: this.handoverStatus,
        }
      });
    },
    async examSchedule() {
      const resClass= await getTrainingClass(this.classId);
      if(resClass.examPaperIds ===null && resClass.examPaperIds ===""){
        this.$message.warning("当前班级暂无考试安排");
        return;
      }
      try {
        const listRes = await listExamSchedule({ trainingClassId: this.classId });
        if (listRes.code !== 200 || !Array.isArray(listRes.rows) || listRes.rows.length === 0) {
          this.$message.warning("当前班级暂无考试安排");
          this.examScheduleList = [];
          this.currentScheduleIndex = 0;
          this.formExamArrangement = {
            examScheduleId: "",
            paperConfigId:"",
            trainingClassId: this.classId,
            examStartTime: "",
            examEndTime: "",
            examDuration: "",
            examAddress: "",
            examWays: ["手机", "电脑"],
            passScore: "",
            publishImmediately: "是",
            publishTime: "",
            autoMakeup: "是",
            makeupTimes: "",
            invigilator: "",
            remark: "",
          };
          this.dialogVisibleExamArrangement = true;
          return;
        }

        this.examScheduleList = listRes.rows;
        this.currentScheduleIndex = 0;
        const firstSchedule = this.examScheduleList[this.currentScheduleIndex];

        const detailRes = await getExamSchedule(firstSchedule.examScheduleId);
        if (detailRes.code !== 200  || detailRes.data.length === 0) {
          this.$message.error("获取考试安排详情失败");
          return;
        }
        this.fillExamScheduleForm(detailRes.data);
        this.dialogVisibleExamArrangement = true;
      } catch (error) {
        this.$message.error("加载考试安排失败，请重试");
        console.error("考试安排加载错误：", error);
      }
    },
    async fillExamScheduleForm(item) {
      const examRes = await getPaperConfig(item.paperConfigId)
      const classExamRes = await getExamInfoById(this.classId);
      // 填充考试表格数据
        if (classExamRes.code === 200 && Array.isArray(classExamRes.data) && classExamRes.data.length > 0) {
          this.exams = classExamRes.data.map(item => ({
            paperConfigId: item.paperConfigId,
            group: item.paperConfigId,
            singleChoiceCount: item.singleChoiceCount,
            multipleChoiceCount: item.multipleChoiceCount,
            judgmentCount: item.judgmentCount,
            totalCount: item.totalCount,
            totalScore: item.totalScore
          })).filter(itemUse => item.paperConfigId===itemUse.paperConfigId);
        } else {
          this.exams = [{
            paperConfigId: "",
            group: '',
            singleChoiceCount: null,
            multipleChoiceCount: null,
            judgmentCount: null,
            totalCount: null,
            totalScore: null
          }];
        }
        console.log(this.exams)
      // 获取项目关联的考试题组
      const res = await getPaperCofigList({
        trainingProjectId: examRes.data.trainingProjectId
      });
      if (res.code === 200 && Array.isArray(res.rows)) {
          this.paperConfigOptions = res.rows;
        }
      const pathwayMap = { "0": "手机", "1": "电脑" };
      this.formExamArrangement = {
        paperConfigId:item.paperConfigId || "",
        examScheduleId: item.examScheduleId || "",
        trainingClassId: item.trainingClassId || this.classId,
        examStartTime: item.examStartTime || "",
        examEndTime: item.examEndTime || "",
        examDuration: item.examDuration ? Number(item.examDuration) : "",
        examAddress: item.examLocation || "",
        examWays: item.examPathway
          ? item.examPathway.split(",").map(key => pathwayMap[key] || "")
          : ["手机", "电脑"],
        passScore: item.examPassScore ? Number(item.examPassScore) : "",
        publishImmediately: item.ifReleaseResultsImmediately === "0" ? "是" : "否",
        publishTime: item.resultsAnnouncementTime || "",
        autoMakeup: item.ifAgreeAutomaticExam === "0" ? "是" : "否",
        makeupTimes: item.examTimes ? Number(item.examTimes) : "",
        invigilator: item.invigilatorId || "",
        remark: item.remark || ""
      };

      if (this.formExamArrangement.publishImmediately === "是") {
        this.formExamArrangement.publishTime = "";
      }
    },
    async handleNextSchedule() {
      if (this.currentScheduleIndex >= this.examScheduleList.length - 1) {
        this.$message.info("已到达最后一条考试安排");
        return;
      }

      this.currentScheduleIndex++;
      const nextSchedule = this.examScheduleList[this.currentScheduleIndex];

      try {
        const detailRes = await getExamSchedule(nextSchedule.examScheduleId);
        if (detailRes.code !== 200  || detailRes.data.length === 0) {
          this.$message.error("获取下一条考试安排失败");
          return;
        }
        this.fillExamScheduleForm(detailRes.data);
      } catch (error) {
        this.$message.error("切换考试安排失败");
        console.error("切换错误：", error);
      }
    },
    removeStudent(id) {
      this.selectedStudents = this.selectedStudents.filter(student => student.id !== id);
      this.selection = [...this.selectedStudents];
      this.single = this.selection.length !== 1;
    },
    handlePublishChange(val) {
      if (val === "是") {
        this.formExamArrangement.publishTime = "";
      }
    },
    validatePublishTime(rule, value, callback) {
      if (this.formExamArrangement.publishImmediately === "否" && !value) {
        callback(new Error("请选择成绩发布时间"));
      } else {
        callback();
      }
    },
    handleSubmitExamArrangement() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        try {
          const submitData = { ...this.formExamArrangement };
          const reversePathwayMap = { "手机": "0", "电脑": "1" };
          submitData.examPathway = submitData.examWays.map(val => reversePathwayMap[val]).join(",");
          submitData.ifReleaseResultsImmediately = submitData.publishImmediately === "是" ? "0" : "1";
          submitData.ifAgreeAutomaticExam = submitData.autoMakeup === "是" ? "0" : "1";
          submitData.examLocation = submitData.examAddress;
          submitData.examPassScore = submitData.passScore;
          submitData.examTimes = submitData.makeupTimes;
          submitData.invigilatorId = submitData.invigilator;
          submitData.resultsAnnouncementTime = submitData.publishTime;
          submitData.paperConfigId =this.paperConfigOptions[this.currentScheduleIndex].paperConfigId

          delete submitData.examWays;
          delete submitData.examAddress;
          delete submitData.passScore;
          delete submitData.makeupTimes;
          delete submitData.invigilator;
          delete submitData.publishImmediately;
          delete submitData.publishTime;
          delete submitData.autoMakeup;

          let res;
          if (submitData.examScheduleId) {
            res = await updateExamSchedule(submitData);
          } else {
            res = await addExamSchedule(submitData);
          }

          if (res.code === 200) {
            this.$message.success(submitData.examScheduleId ? "编辑成功" : "新增成功");
            this.dialogVisibleExamArrangement = false;
            this.getList();
            this.examScheduleList = [];
            this.currentScheduleIndex = 0;
          } else {
            this.$message.error(res.msg || "提交失败");
          }
        } catch (error) {
          this.$message.error("提交接口调用失败，请重试");
          console.error("提交错误：", error);
        }
      });
    },
    handleCancelExamArrangement() {
      this.dialogVisibleExamArrangement = false;
      this.$refs.formRef.resetFields();
    },

    // -------------- 移植：学员通知弹窗功能（来自培训班页面） --------------
    openNoticeDialog(row) {
      this.initNoticeForm();
      this.noticeDialogVisible = true;
      // 若从表格行点击，默认选中当前学员
      // if (row) {
      //   this.noticeForm.range = "selected";
      //   this.noticeForm.selectedUsers = [row.id];
      // }
    },
    // 初始化通知表单
    initNoticeForm() {
      this.noticeForm = {
        title: '',
        content: '',
        range: 'all',
        selectedUsers: [],
        sendTypes: []
      };
      this.$nextTick(() => {
        if (this.$refs.noticeForm) this.$refs.noticeForm.clearValidate();
      });
    },
    // 发送范围切换（全部/指定）
    handleRangeChange(newRange) {
      if (newRange === 'all') {
        this.noticeForm.selectedUsers = this.allUsers.map(user => user.id);
      } else {
        this.noticeForm.selectedUsers = [];
      }
      this.$nextTick(() => {
        if (this.$refs.noticeForm) this.$refs.noticeForm.clearValidate('selectedUsers');
      });
    },
    // 清空选中学员
    handleSelectClear() {
      this.noticeForm.selectedUsers = [];
    },
    // 远程搜索学员
    queryUsers(query) {
      if (!query) {
        this.userOptions = [...this.allUsers];
        return;
      }
      this.userLoading = true;
      setTimeout(() => {
        this.userOptions = this.allUsers.filter(user =>
          user.name.includes(query) || user.idCard.includes(query)
        );
        this.userLoading = false;
      }, 300);
    },
    // 提交通知（调用移植API）
    async submitNotice() {
      this.$refs.noticeForm.validate(async valid => {
        if (valid) {
          this.noticeLoading = true;
          try {
            const params = {
              sendType: this.noticeForm.range === 'all' ? "1" : "2",
              studentIds: this.noticeForm.range === 'all' ? [] : this.noticeForm.selectedUsers,
              isSms: this.noticeForm.sendTypes.includes('0') ? "1" : "0",
              isPortal: this.noticeForm.sendTypes.includes('1') ? "1" : "0",
              noticeTitle: this.noticeForm.title,
              noticeContent: this.noticeForm.content,
              sendTime: new Date().toLocaleString('zh-CN', {
                year: 'numeric', month: '2-digit', day: '2-digit',
                hour: '2-digit', minute: '2-digit', second: '2-digit',
                hour12: false
              }).replace(/\//g, '-'),
              trainingClassId: this.classId // 关联当前考试班级
            };
            const res = await studentNoticeProcess(params);
            if (res.code === 200) {
              this.$message.success('通知发送成功');
              this.noticeDialogVisible = false;
            } else {
              this.$message.error(res.msg || '通知发送失败');
            }
          } catch (err) {
            this.$message.error('通知发送失败：' + (err.msg || err.message));
          } finally {
            this.noticeLoading = false;
          }
        }
      });
    },
    // 关闭通知弹窗
    handleNoticeDialogClose() {
      this.noticeDialogVisible = false;
    },

    // -------------- 移植：学员备注弹窗功能（来自培训班页面） --------------
    openRemarkDialog(row) {
      let targetRow =null;
      // 优先获取行数据，无则取选中数据
      if(row.id !==undefined){
        targetRow =row
      }else{
        targetRow = this.selection && this.selection.length > 0 ? this.selection[0] : null;
        if (!targetRow) return this.$message.warning('请选择一个学员');
      }

      this.remarkForm.studentId = targetRow.id; // 关联学员ID
      this.remarkDialogTitle = `学员【${targetRow.name}】备注`;
      this.remarkLoading = true;

      // 加载备注历史（调用移植API）
      this.loadRemarkHistory();
    },
    // 加载备注历史
    async loadRemarkHistory() {
      try {
        const res = await listRemarksByParams({
          foreignId: this.remarkForm.studentId,
          remarkType: "4" // 备注类型：学员备注（与培训班页面一致）
        });
        this.remarkHistory = res.rows.map(item => ({
          time: item.createTime,
          operator: item.createBy,
          content: item.remarks
        }));
      } catch (err) {
        this.$message.error('加载备注历史失败：' + (err.msg || err.message));
        this.remarkHistory = [];
      } finally {
        this.remarkLoading = false;
        this.remarkDialogVisible = true;
      }
    },
    // 重置备注表单
    resetRemarkForm() {
      this.$nextTick(() => {
        if (this.$refs.remarkForm) this.$refs.remarkForm.resetFields();
        this.remarkForm.remarks = "";
        this.remarkForm.studentId = null;
      });
    },
    // 提交备注（调用移植API）
    async submitRemark() {
      this.$refs.remarkForm.validate(async valid => {
        if (valid) {
          this.remarkSubmitting = true;
          try {
            const res = await addRemarks({
              foreignId: this.remarkForm.studentId,
              remarkType: "4",
              remarks: this.remarkForm.remarks
            });
            if (res.code === 200) {
              this.$message.success('备注提交成功');
              this.remarkDialogVisible = false;
              this.getList(); // 刷新表格显示最新备注
            } else {
              this.$message.error(res.msg || '备注提交失败');
            }
          } catch (err) {
            this.$message.error('备注提交失败：' + (err.msg || err.message));
          } finally {
            this.remarkSubmitting = false;
          }
        }
      });
    },

    // -------------- 移植：班级二维码功能 → 考试二维码（来自培训班页面） --------------
    handleQrCode() {
      // if (!this.selection || this.selection.length !== 1) {
      //   return this.$message.warning('请选择单个学员生成考试二维码');
      // }
      // 可扩展：根据学员ID/考试ID动态获取二维码URL
      // 此处暂用移植的默认URL，实际项目需替换为接口请求
      this.qrCodeUrl = 'http://127.0.0.1:9300/statics/2025/09/19/1_20250919113028A006.jpg';
      this.qrcodeError = false;
      this.qrCodeDialogVisible = true;
    },
    // 重置二维码状态
    resetCode() {
      this.qrcodeError = false;
      this.qrCodeUrl = '';
    },
    // 二维码加载错误处理
    handleQrcodeError() {
      this.qrcodeError = true;
    },

    // -------------- 原有考试详情方法 --------------
    handleExamDetail(row) {
      if (row.id !==undefined && row.id !==null ) {
        this.$message.warning("请选择学员");
        this.currentStudent = { ...row };
        this.loadExamRecords(row.id);
      }else{
        this.currentStudent = this.selection[0]
        this.loadExamRecords(this.selection[0].id);
      }
      this.examDetailDialogVisible = true;
    },
    async loadExamRecords(studentId) {
      const res = await getExamRecordInfo({studentId:this.currentStudent.id ,trainingClassId:this.classId})
      this.examRecords = res.rows.map(item =>{
        return {
          examDate: item.examStartTime,
          score: item.totalScore || "0",
          status: item.examResult ==="0"?"通过":"未通过",
          originalRecord:item
        }
      })

    },
    handleCloseExamDetail() {
      this.examDetailDialogVisible = false;
      this.currentStudent = {};
    },

    // -------------- 原有多次补考方法 --------------
    handleMakeupExam() {
      if (!this.selection || this.selection.length === 0) {
        this.$message.warning("请选择需要补考的学员");
        return;
      }
      this.selectedStudents = [...this.selection];
      this.makeupExamDialogVisible = true;
    },
    handleCloseMakeupExam() {
      this.makeupExamDialogVisible = false;
      this.$refs.makeupExamFormRef.resetFields();
    },
    handleSubmitMakeupExam() {
      this.$refs.makeupExamFormRef.validate((valid) => {
        if (valid) {
          this.$message.success("补考设置提交成功");
          this.makeupExamDialogVisible = false;
        }
      });
    },
    async handlePrevSchedule() {
  if (this.currentScheduleIndex <= 0) {
    this.$message.info("已到达第一条考试安排");
    return;
  }

  this.currentScheduleIndex--;
  const prevSchedule = this.examScheduleList[this.currentScheduleIndex];

  try {
    const detailRes = await getExamSchedule(prevSchedule.examScheduleId);
    if (detailRes.code !== 200  || detailRes.data.length === 0) {
      this.$message.error("获取上一条考试安排失败");
      return;
    }
    this.fillExamScheduleForm(detailRes.data);
  } catch (error) {
    this.$message.error("切换考试安排失败");
    console.error("切换错误：", error);
  }
},

    // -------------- 通用方法 --------------
    handleSearch() {
      this.pagination.currentPage = 1;
      this.getList();
    },
    handleReset() {
      this.searchForm = { name: "", idCard: "", isPass: "", examStatus: "" };
      this.pagination.currentPage = 1;
      this.getList();
    },
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },
    handleRefresh() {
      this.getList();
      this.$message.success("刷新成功");
    },
    handleSelectionChange(selection) {
      this.selection = selection;
      this.single = selection.length !== 1;
      this.selectedStudents = [...selection];
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getList();
    }
  },
};
</script>

<style scoped>
.exam-management-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 64px);
}
.class-info { margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid #eee; }
.info-item { margin-right: 20px; font-weight: 500; }
.search-form { margin-bottom: 20px; }
.operation-buttons { margin-bottom: 20px; }
.operation-buttons .el-button { padding: 6px 10px; }
.pagination-container { margin-top: 20px; text-align: right; }
.exam-form { padding: 10px 0; }
.el-row { margin-bottom: 15px; }
.form-footer { text-align: center; margin-top: 20px; padding-top: 10px; border-top: 1px solid #eee; }
.remark-textarea { width: 100%; }

/* 选中的学员样式 */
.selected-students {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.selected-students h4 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

/* 二维码样式（移植自班级二维码，适配考试场景） */
.qr-code-container {
  text-align: center;
  padding: 20px 0;
}
.qr-code-image {
  width: 100%;
  max-width: 200px;
  margin: 0 auto;
  border: 1px solid #eee;
  padding: 10px;
}
.loading-indicator {
  padding: 50px 0;
  color: #606266;
}
.qr-code-desc {
  margin-top: 15px;
  color: #606266;
  font-size: 14px;
}
/* 二维码错误提示（移植核心样式） */
.qrcode-error {
  color: #f56c6c;
  font-size: 14px;
  margin-top: 20px;
  padding: 30px 0;
}

/* 考试详情样式 */
.exam-detail-container {
  padding: 10px 0;
}
.detail-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #eee;
}
.detail-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}
.section-title {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  color: #303133;
  padding-left: 5px;
  border-left: 3px solid #409eff;
}
.detail-item {
  margin-bottom: 12px;
  line-height: 1.8;
}
.item-label {
  display: inline-block;
  color: #606266;
  width: 100px;
  font-weight: 500;
}
.item-value {
  color: #303133;
}

/* 移植：学员通知弹窗样式（来自培训班页面） */
.selected-users-form-item {
  margin-top: 10px;
}
.selected-count {
  margin-top: 5px;
  font-size: 12px;
  color: #666;
}

/* 移植：学员备注弹窗样式（来自培训班页面） */
::v-deep .dialog-remark .el-textarea {
  width: 100%;
}
::v-deep .dialog-remark .el-table {
  margin-top: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-col { width: 100% !important; flex: none !important; }
  .operation-buttons {
    display: flex;
    flex-wrap: wrap;
  }
  .operation-buttons .el-button {
    margin-bottom: 10px;
  }
  .item-label {
    width: 80px;
  }
}
/* 考卷详情弹窗样式 */
.exam-paper-container {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.paper-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.paper-info {
  display: flex;
  gap: 20px;
  color: #606266;
}

.questions-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.question-item {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-weight: 500;
}

.question-index {
  margin-right: 10px;
  color: #409eff;
}

.question-type {
  font-size: 13px;
  color: #67c23a;
  background-color: rgba(103, 194, 58, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
  margin-left: 10px;
}

.question-content {
  margin-bottom: 10px;
  line-height: 1.6;
}

.question-options {
  margin: 10px 0 15px 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 5px 10px;
  border-radius: 4px;
}

.option-label {
  min-width: 20px;
  margin-right: 10px;
  font-weight: 500;
}

.correct-option {
  background-color: rgba(103, 194, 58, 0.1);
  border-left: 3px solid #67c23a;
}

.student-option {
  background-color: rgba(64, 158, 255, 0.1);
  border-left: 3px solid #409eff;
}

.question-answer {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #eee;
  font-size: 14px;
}

.answer-label {
  color: #67c23a;
  margin-bottom: 5px;
}

.student-answer {
  color: #409eff;
  margin-bottom: 5px;
}

.answer-analysis {
  color: #f56c6c;
  margin-top: 5px;
  padding: 5px 10px;
  background-color: rgba(245, 108, 108, 0.1);
  border-radius: 4px;
}
</style>
